<template>
  <div class="salfjas">
    <div id="results">
      <textarea id="result"></textarea>
    </div>
    
    <div id="sendVal">
      <input id="question" type="text">
      <button id="btn">发送信息</button>
    </div>
  </div>
</template>

<script>
import * as base64 from 'base-64';
import CryptoJs from 'crypto-js';

export default {
  name: 'ChatComponent',
  data() {
    return {
      questionInput: null,
      sendMsgBtn: null,
      result: null,
      requestObj: {
        APPID: 'b8d4e8e0',
        APISecret: 'YjRiZDcwZTNjNTZmZWQ5MTRmYjU0NmVj',
        APIKey: '52b02c7d1a8b4b4371cf8ebc4e745439',
        Uid: "redrun",
        sparkResult: ''
      }
    };
  },
  methods: {
    async sendMsg() {
      let myUrl = await this.getWebsocketUrl();
      let inputVal = this.questionInput.value;
      let socket = new WebSocket(myUrl);

      socket.addEventListener('open', (event) => {
        console.log('开启连接！！', event);
        let params = {
          "header": {
            "app_id": this.requestObj.APPID,
            "uid": "redrun"
          },
          "parameter": {
            "chat": {
              "domain": "lite",
              "temperature": 0.5,
              "max_tokens": 1024,
            }
          },
          "payload": {
            "message": {
              "text": [
                { "role": "user", "content": "你是谁" },
                { "role": "assistant", "content": "我是AI助手" },
                { "role": "user", "content": inputVal }
              ]
            }
          }
        };
        console.log("发送消息");
        socket.send(JSON.stringify(params));
      });

      socket.addEventListener('message', (event) => {
        let data = JSON.parse(event.data);
        this.requestObj.sparkResult += data.payload.choices.text[0].content;
        if (data.header.code !== 0) {
          console.log("出错了", data.header.code, ":", data.header.message);
          socket.close();
        }
        if (data.header.code === 0) {
          if (data.payload.choices.text && data.header.status === 2) {
            this.requestObj.sparkResult += data.payload.choices.text[0].content;
            setTimeout(() => {
              socket.close();
            }, 1000);
          }
        }
        this.addMsgToTextarea(this.requestObj.sparkResult);
      });

      socket.addEventListener('close', (event) => {
        console.log('连接关闭！！', event);
        this.requestObj.sparkResult = this.requestObj.sparkResult + "&#10;";
        this.addMsgToTextarea(this.requestObj.sparkResult);
        this.questionInput.value = '';
      });

      socket.addEventListener('error', (event) => {
        console.log('连接发送错误！！', event);
      });
    },

    getWebsocketUrl() {
      return new Promise((resolve, reject) => {
        let url = "wss://spark-api.xf-yun.com/v1.1/chat";
        let host = "spark-api.xf-yun.com";
        let apiKeyName = "api_key";
        let date = new Date().toGMTString();
        let algorithm = "hmac-sha256";
        let headers = "host date request-line";
        let signatureOrigin = `host: ${host}\ndate: ${date}\nGET /v1.1/chat HTTP/1.1`;
        let signatureSha = CryptoJs.HmacSHA256(signatureOrigin, this.requestObj.APISecret);
        let signature = CryptoJs.enc.Base64.stringify(signatureSha);

        let authorizationOrigin = `${apiKeyName}="${this.requestObj.APIKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`;

        let authorization = base64.encode(authorizationOrigin);

        url = `${url}?authorization=${authorization}&date=${encodeURI(date)}&host=${host}`;

        resolve(url);
      });
    },

    addMsgToTextarea(text) {
      this.result.innerHTML = text;
    }
  },
  mounted() {
    this.questionInput = document.querySelector("#question");
    this.sendMsgBtn = document.querySelector("#btn");
    this.result = document.querySelector("#result");

    // 点击发送信息按钮
    this.sendMsgBtn.addEventListener('click', () => {
      this.sendMsg();
    });

    // 输入完信息点击enter发送信息
    this.questionInput.addEventListener('keydown', (event) => {
      if (event.key === 'Enter') {
        event.preventDefault(); // 阻止默认行为，防止表单提交
        this.sendMsg();
      }
    });
  }
};
</script>

<style>
.salfjas {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 8px;
}

#results {
  margin-bottom: 20px;
}

#result {
  width: 100%;
  height: 200px;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  resize: none;
}

#sendVal {
  display: flex;
  align-items: center;
}

#question {
  flex: 1;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  margin-right: 10px;
}

#btn {
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

#btn:hover {
  background-color: #0056b3;
}
</style>
